package com.zhang.controller.member;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.email.EmailUtil;
import com.zhang.common.util.redis.RedisUtil;
import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;
import com.zhang.member.dto.UserSearchDTO;
import com.zhang.member.entity.MemberUser;
import com.zhang.member.service.IMemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前台会员用户表 前端控制器
 * </p>
 *
 * @author 创世神
 * @since 2023-10-31
 */
@RestController
@RequestMapping("/member")
@Slf4j
public class MemberUserController {
    @Autowired
    private IMemberUserService memberUserService;
    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${my.emailKey}")
    private String emailKey;

    /**
     * 用户注册
     *
     * @param user
     * @return {@link R}
     */
    @PostMapping("enroll")
    public R memberEnroll(@RequestBody MemberUser user) {
        R r = memberUserService.enroll(user);
        return r;
    }

    /**
     * 用户登录
     *
     * @param user
     * @return {@link R}
     */
    @PostMapping("login")
    public R memberLogin(@RequestBody MemberUser user, HttpServletRequest httpServletRequest) {
        R r = memberUserService.login(user,httpServletRequest);
        return r;
    }

    /**
     * 修改自己的信息
     *
     * @param user
     * @return {@link R}
     */
    @PostMapping("/update/byMyself")
    @SaCheckLogin
    public R updateMember(@RequestBody MemberUser user) {
        /*下面是不能被修改的值*/
        user.setPassword(null);
        user.setMd5Salt(null);
        user.setUserName(null);
        if (!StrUtil.isBlank(user.getEmail())) {
            String value = redisUtil.getToString(emailKey + ":" + user.getEmail());
            redisUtil.del(emailKey + ":" + user.getEmail());//删除
            if (!user.getCode().equals(value)) {
//如果不合法不能保存
                user.setEmail(null);
                log.error("邮箱不合法！");
                memberUserService.updateById(user);
                return RUtils.err("邮箱校验失败");
            }
        }
        memberUserService.updateById(user);
        return RUtils.successMsg("修改成功!");
    }

    /**
     * 获取登录人的详细信息
     *
     * @return {@link R}
     */
    @GetMapping("get/my/info")
    public R getMyInfo() {
        R r = memberUserService.getMyInfo();
        return r;
    }

    @GetMapping("logout")
    public R logout() {
        StpUtil.logout();
        return RUtils.successMsg("注销成功！");
    }

    @GetMapping
    @SaCheckRole("admin")
    public R getMemberById(@RequestParam("userId") String userId) {
        MemberUser byId = memberUserService.getById(userId);
        return RUtils.successData(byId);
    }

    /**
     * 发送邮箱校验验证码
     *
     * @param email
     * @return {@link R}
     */
    @PostMapping("get/email/verifyCode")
    public R sendMsg(@RequestBody String email) {
        String s = RandomUtil.randomNumbers(5);
//        以用户邮箱作为key
        redisUtil.set(emailKey, email, 1, TimeUnit.MINUTES);
        emailUtil.sendMailByString(email, "验证码", s);
        return RUtils.successMsg("你已经发送成功!");
    }

    @PutMapping
    public R ModifyUser(@RequestBody MemberUser memberUser) {
        memberUserService.updateById(memberUser);
        return RUtils.successMsg("修改成功");
    }

    @GetMapping("list")
    @SaCheckRole("admin")
    public R getMembers(UserSearchDTO userSearchDTO) {
        IPage<MemberUser> memberUserIPage = memberUserService.getMembers(userSearchDTO);
        return RUtils.successData(memberUserIPage);
    }
}
